package com.honeywen.mymvc.leetcode;

/**
 * @author weiw@opera.com
 * @date 2018/8/18 下午7:02
 */
public class Solution {


    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode head = null, tail = null;

        while (l1 != null && l2 != null) {

            ListNode node = null;
            if (l1.val < l2.val) {
                node = l1;
                l1 = l1.next;
            } else {
                node = l2;
                l2 = l2.next;
            }

            if (head == null) {

                head = tail = node;

            } else {

                tail.next = node;
                tail = tail.next;

            }

        }

        ListNode rest = l1 == null ? l2 : l1;

        if (rest != null) {
            if (head != null && tail != null) {
                tail.next = rest;
            } else {
                head = rest;
            }
        }
        return head;

    }

    private ListNode mergeTheRest(ListNode rest, ListNode head, ListNode tail) {

        if (rest != null) {
            if (head != null && tail != null) {
                tail.next = rest;
            } else {
                head = rest;
            }
        }

        return head;
    }

    public static void main(String[] args) {


        Solution solution = new Solution();

        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);

        ListNode listNode = solution.mergeTwoLists(l1, l2);
        while (listNode.next != null) {
            System.out.print(listNode.val + "->");
            listNode = listNode.next;
        }
    }
}
